package DAOS;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import Hibernate.HibernateUtil;
import Negocio.Medico;
import Negocio.Turno;

public class TurnoDAO {

private static TurnoDAO instancia = null;
	
	private static SessionFactory sf = null;

	public static TurnoDAO getInstancia(){
		if(instancia == null){
			sf = HibernateUtil.getSessionFactory();
			instancia = new TurnoDAO();
		} 
		return instancia;
	}
	
	public void guardarTurno(Turno t){

		Session session = sf.openSession();
		session.beginTransaction();
		session.persist(t);
		session.flush();
		session.getTransaction().commit();
		session.close();

	}


	public void eliminarTurno(Turno t){

		Session session = sf.openSession();
		session.beginTransaction();
		session.delete(t);
		session.flush();
		session.getTransaction().commit();
		session.close();
		

	}


	public void modificarTurno(Turno t){

		Session session = sf.openSession();
		session.beginTransaction();
		session.update(t);
		session.flush();
		session.getTransaction().commit();
		session.close();

	}


	public List<Object[]> listarTurnos(Date hora) {

		Session session = sf.openSession();
		Query q = session.createQuery
		(
				"SELECT t.fechaYhora, m.nombre, p.nombre, t.estado" +
				"FROM Turno t INNER JOIN t.Medico as m INNER JOIN t.Paciente as p" +
				"WHERE t.fechaYhora = " + hora
		);
		
		@SuppressWarnings("unchecked")
		List<Object[]> turnos = new ArrayList<Object[]>(q.list());
		session.close();
		return turnos;
		
	}
	
	public List<Turno> cargarTurnosFecha (Date fecha){
		Session session = sf.openSession();
		Query q = session.createQuery(
				"SELECT t.fechaYhora, m.nombre, p.nombre, t.estado" +
				"FROM Turno t INNER JOIN t.Medico as m INNER JOIN t.Paciente as p" +
				"WHERE t.fechaYhora = " + fecha
		);
		
		@SuppressWarnings("unchecked")
		List<Turno> tt = new ArrayList<Turno>(q.list());
		
		session.close();
		
		return tt;
	}
}
